import React, { Component, Fragment } from 'react';
import { Modal, Upload, Icon, Row, Col, message, Progress } from 'antd';
import axios from 'axios';
import { stringify } from 'qs';
import prompt from '@/components/Prompt';
import { checkSuffix } from '@/utils/common';
import styles from './index.less';
import { thisExpression } from '@babel/types';

export default class AdUpload extends Component {
  static defaultProps = {
    urlType: 'ems',
    mode: 'swiper',
    fileLength: 5,
    showUpload: true,
  };

  constructor(props) {
    super(props);
    const { urlType, actionName } = props;
    const token = localStorage.getItem('token');
    this.state = {
      visible: false,
      previewImage: '',
      fileList: [],
    };
    this.token = token;
    // this.actionName = `/server/api/zuul/${urlType}/attachment/uploadFile`;
    this.actionName = actionName
      ? actionName
      : `/server/api/api/OCS/Order/UploadFileTemp?${stringify({ token })}`;
    this.readName = `/server/api/${urlType}/attachment/viewpage`;
  }

  componentDidMount() {
    const { value } = this.props;
    if (value && value.length > 0) {
      this.setFileList(value);
    }
  }

  componentWillReceiveProps(nextProps) {
    const { value } = nextProps;
    if (value && value.length > 0) {
      this.setFileList(value);
    } else {
      this.setState({ fileList: [] });
    }
  }

  setFileList = value => {
    const actionName = this.actionName;
    const readName = this.readName;

    const fileList = value.map(file => {
      if (file.uid) {
        return file;
      }
      const { fileId, fileToken, fileUrl, fileName, fileType, isUploadFileSYS } = file;

      /*
      files数据格式：
      {
        fileId: "6211bab5-22f2-4ee9-b413-794c0f95fdbd"
        fileName: "康宁网上下单导入模版-v1.2.xlsx"
        fileType: ".xlsx"
        fileUrl: "6211bab5-22f2-4ee9-b413-794c0f95fdbd"
        flag: 0
        folderName: "下单导入文件",
        isUploadFileSYS: false,//是否来源系统，下载路径  http://192.168.1.127:8088/file-manager/downloadFile?appid=111&filetoken=0192fc9f414f4d3cb6da8cdecb64be31
      }
      */
      let data = {
        uid: fileId,
        status: 'done',
        fileUrl: fileUrl || '',
        id: fileId,
        name: fileName || '附件',
        fileType,
        fileToken: fileId,
        isUploadFileSYS,
      };
      return data;
    });

    this.setState({ fileList });
  };

  handleCancel = () => {
    const { visible } = this.state;
    this.setState({ visible: !visible });
  };

  handlePreview = file => {
    const { mode, value, handlePreview } = this.props;
    if (file.response) {
      prompt({
        type: 'warn',
        title: '温馨提示',
        content: '我们暂不支持未保存的文件查看和下载,请先保存！',
      });
      return;
    }
    if (mode === 'swiper') {
      if (handlePreview)
        handlePreview(
          value,
          value.findIndex(v => (v.fileId ? v.fileId === file.id : v.id === file.id))
        );
    }
  };

  handleChange = ({ fileList }) => {
    fileList.map(file => {
      if (file.size && !file.response) {
        const formData = new FormData();
        fileList.forEach(file => {
          formData.append('file', file.originFileObj);
        });
        axios
          .post(this.actionName, formData, {
            headers: {
              token: this.token,
            },
            onUploadProgress: ({ total, loaded }) => {
              const percent = Number(Math.round((loaded / total) * 100).toFixed(0));
              file.percent = percent;
              const newFileList = [
                ...this.state.fileList.filter(oldFile => oldFile.uid !== file.uid),
                file,
              ];
              this.setState({
                fileList: newFileList,
              });
              this.triggerChange(newFileList);
            },
          })
          .then(({ data: response }) => {
            const { code, message } = response;
            let newFileList = [];
            if (code === 0) {
              file.response = response;
              newFileList = [
                ...this.state.fileList.filter(oldFile => oldFile.uid !== file.uid),
                file,
              ];
            } else {
              if (code === 401) {
                // 401：未登录,跳转到首页
                router.push('/user/login');
                localStorage.removeItem('token');
                newFileList = this.state.fileList.filter(oldFile => oldFile.uid !== file.uid);
                prompt({ type: 'error', title: '上传错误', content: message });
              }
              newFileList = this.state.fileList.filter(oldFile => oldFile.uid !== file.uid);
              prompt({ type: 'error', title: '上传错误', content: message });
            }
            this.setState({
              fileList: newFileList,
            });
            this.triggerChange(newFileList);
          })
          .catch(() => {
            const newFileList = this.state.fileList.filter(oldFile => oldFile.uid !== file.uid);
            this.setState({
              fileList: newFileList,
            });
            this.triggerChange(newFileList);
            prompt({ type: 'error', title: '上传错误', content: '上传出错！' });
          });
      }
    });
  };

  remove = (e, uid) => {
    e.stopPropagation();
    const { fileList } = this.state;
    const newFileList = fileList.filter(file => file.uid !== uid);
    this.setState({ fileList: newFileList });
    this.triggerChange(newFileList);
  };

  triggerChange = value => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(value);
    }
  };

  isImage = name => {
    const arr = ['.jpg', '.jpeg', '.png', '.gif'];
    // name = name.substring(name.lastIndexOf('.'), name.length) || '.jpg';
    name = name || '.jpg';
    return arr.includes(name.toLowerCase());
  };

  render() {
    const { visible, previewImage, fileList } = this.state;
    const { fileLength, showUpload, onChange, ...rest } = this.props;
    const actionName = this.actionName;

    const UploadButton = (
      <div>
        <Icon type="plus" />
        上传
      </div>
    );
    return (
      <Fragment>
        {/* <Modal visible={visible} footer={null} onCancel={this.handleCancel}>
          <img alt="image" style={{ width: '100%' }} src={previewImage} />
        </Modal> */}
        <Row type="flex" className={styles.upload}>
          <Col>
            <Row type="flex" style={{ width: '100%' }}>
              {fileList.map(file => (
                <Col
                  key={file.uid}
                  className={styles['upload-file']}
                  onClick={() => {
                    this.handlePreview(file);
                  }}
                >
                  <Icon
                    type={this.isImage(file.fileType) ? 'picture' : 'file'}
                    className={styles['upload-file-icon']}
                  />
                  <div title={file.name} className={styles['upload-file-name']}>
                    {file.name}
                  </div>
                  {file.percent && file.percent !== 100 && (
                    <Progress percent={file.percent} showInfo={false} size="small" />
                  )}
                  {showUpload && !this.props.disabled && (
                    <div
                      className={styles['upload-file-close']}
                      onClick={e => {
                        this.remove(e, file.uid);
                      }}
                    >
                      <Icon type="close" />
                    </div>
                  )}
                </Col>
              ))}
            </Row>
          </Col>
          <Col>
            <Upload
              // action={actionName}
              // headers={{ token: this.token }}
              listType="picture-card"
              fileList={[]}
              onChange={this.handleChange}
              beforeUpload={() => {
                return false;
              }}
              {...rest}
            >
              {fileList.length >= fileLength ? null : showUpload && UploadButton}
            </Upload>
          </Col>
        </Row>
      </Fragment>
    );
  }
}
